package com.mingtu.jgspatrol.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.FrameLayout;

import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.common.Eventbus.MyEventBus;
import com.mingtu.common.callback.StringDialogCallback;
import com.mingtu.common.utils.ActivityUtil;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.IntentUtils;
import com.mingtu.common.utils.UIUtils;
import com.mingtu.jgspatrol.R;
import com.mingtu.jgspatrol.base.MyBaseActivity;
import com.mingtu.jgspatrol.databinding.ActivityIndexFireSendBinding;
import com.mingtu.jgspatrol.utils.MyConstant;

import org.greenrobot.eventbus.EventBus;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

public class IndexFireSendActivity extends MyBaseActivity<ActivityIndexFireSendBinding> {
    private JSONArray peopleInfoList = null;
    private Timer timer;
    private String[] peopleArray = null;
    private String[] mobileArray = null;
    private int[] userIdArray = null;
    private int MyRequestCode = 100;
    private String fireId;
    private int userId;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_index_fire_send;
    }

    @Override
    protected void initView() {
        setModuleTitle("发布火情任务");
    }

    @Override
    protected void initData() {
        addClickListener(this, binding.layoutPeople, binding.layoutTime, binding.submit);
    }


    @Override
    protected void getData() {
        fireId = getIntent().getStringExtra("fireId");
        if (StringUtils.isEmpty(fireId)) {
            ToastUtils.showLong(getResources().getString(R.string.data_error));
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.layout_people:
                Bundle bundle = new Bundle();
                bundle.putBoolean("isMultipleChoice", true);
                IntentUtils.getInstance().readyGoForResult(ActivityUtil.getTopActivity(), SelectPeopleActivity.class, MyRequestCode, bundle);
                break;
            case R.id.layout_time:
                initTimePicker();
                break;
            case R.id.submit:

                if (peopleInfoList == null) {
                    ToastUtils.showLong("请选择任务接收人员！");
                    return;
                }

                if (StringUtils.isEmpty(UIUtils.getTextView(binding.tvTime)) || binding.tvTime.getText().toString().equals(getResources().getString(R.string.text_chose_time))) {
                    ToastUtils.showLong("请选择截止时间！");
                    return;
                }
                addSendFireTask();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == MyRequestCode) {
            if (data != null) {
                String infoStr = data.getStringExtra("infoStr");
                JSONObject object = JSON.parseObject(infoStr);
                peopleInfoList = object.getJSONArray("peopleInfoList");

                if (peopleInfoList != null) {
                    int size = peopleInfoList.size();
                    if (size > 0) {
                        peopleArray = new String[size];
                        mobileArray = new String[size];
                        userIdArray = new int[size];
                        for (int i = 0; i < size; i++) {
                            JSONObject objectItem = (JSONObject) peopleInfoList.get(i);
                            String name = objectItem.getString("name");
                            String mobile = objectItem.getString("mobile");
                            int userId = objectItem.getInteger("userId");
                            peopleArray[i] = name;
                            mobileArray[i] = mobile;
                            userIdArray[i] = userId;
                        }
                        binding.tvName.setText(peopleArray[0]);
                        userId = userIdArray[0];
                    }
                }
            }
        }

    }

    //时间选择器
    private void initTimePicker() {
        //获取系统的日期
        Calendar selectedDate = Calendar.getInstance();
        int year = selectedDate.get(Calendar.YEAR);
        int month = selectedDate.get(Calendar.MONTH);
        int day = selectedDate.get(Calendar.DAY_OF_MONTH);
        int hour = selectedDate.get(Calendar.HOUR_OF_DAY);
        int minute = selectedDate.get(Calendar.MINUTE);
        int second = selectedDate.get(Calendar.SECOND);


        Calendar startDate = Calendar.getInstance();

        //结束时间
        Calendar endDate = Calendar.getInstance();
        endDate.add(Calendar.YEAR, 0);
        endDate.add(Calendar.MONTH, 3);
        endDate.add(Calendar.DAY_OF_MONTH, 0);
        endDate.add(Calendar.HOUR_OF_DAY, 0);
        endDate.add(Calendar.MINUTE, 0);
        endDate.add(Calendar.SECOND, 0);


        TimePickerView pvTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调

                Calendar deadlineTime = Calendar.getInstance();
                deadlineTime.setTime(date);
                int sYear = deadlineTime.get(Calendar.YEAR);
                int sMonth = deadlineTime.get(Calendar.MONTH);
                int sDay = deadlineTime.get(Calendar.DAY_OF_MONTH);

                deadlineTime.set(sYear, sMonth, sDay, 23, 59, 59);

                Date myDate = deadlineTime.getTime();

                String deadlineTimeStr = UIUtils.getTime2(myDate);
                binding.tvTime.setText(deadlineTimeStr);
                binding.tvTime.setTextColor(getResources().getColor(R.color.text_color333));

            }
        })
                .setType(new boolean[]{true, true, true, false, false, false})//分别对应年月日时分秒，默认全部显示
                .setContentTextSize(20)//滚轮文字大小
                .setDividerColor(Color.LTGRAY)//设置分割线的颜色
                .setTitleBgColor(getResources().getColor(R.color.black_eee))
                .setCancelColor(getResources().getColor(R.color.text_cancel_color))
                .setSubmitColor(getResources().getColor(R.color.text_submit_color))
                .setTextColorCenter(getResources().getColor(R.color.colorPrimary))
                .setBgColor(Color.WHITE)
                .isDialog(true)
                .setOutSideColor(getResources().getColor(R.color.transparent))
                .setRangDate(startDate, endDate)//起始终止年月日设定
                .setLabel("年", "月", "日", "时", "分", "秒")
                .build();


        Dialog mDialog = pvTime.getDialog();
        if (mDialog != null) {

            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    Gravity.BOTTOM);

            params.leftMargin = 0;
            params.rightMargin = 0;
            pvTime.getDialogContainerLayout().setLayoutParams(params);
            Window dialogWindow = mDialog.getWindow();
            if (dialogWindow != null) {
                dialogWindow.setWindowAnimations(com.bigkoo.pickerview.R.style.picker_view_slide_anim);//修改动画样式
                dialogWindow.setGravity(Gravity.BOTTOM);//改成Bottom,底部显示
            }
        }

        pvTime.show();
    }


    /**
     * 添加下发任务
     */
    private void addSendFireTask() {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("fireId", fireId);
        hashMap.put("userId", userId);
        hashMap.put("finishTime", binding.tvTime.getText());
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_FIRE_NOTICE_SEND)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(this) {


                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {

                            JSONObject jsonObject = JSON.parseObject(result);
                            String msg = jsonObject.getString("msg");
                            if (msg.equals(Constant.RESULT_SUCCESS)) {
                                ToastUtils.showLong("下发成功！");
                                //实例化Timer类 ,守护线程，不在后台一直运行

                                timer = new Timer(true);
                                timer.schedule(new TimerTask() {
                                    public void run() {
                                        ActivityUtils.finishActivity(IndexFireSendActivity.class);
                                        ActivityUtils.finishActivity(IndexFireDetails1Activity.class);
                                        EventBus.getDefault().post(new MyEventBus(MyConstant.REFRESH_FIRE_NOTICE_DATA));
                                    }
                                }, Constant.TIMER_TIME);
                            }
                        }
                    }
                });
    }

}